package admin

import (
	"archive/zip"
	"fmt"
	"io"
	"os"
	"path"
	"strconv"
	"strings"
	"tcsc/controllers/mobile"
	"tcsc/models"
	"tcsc/sword"

	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/astaxie/beego"
)

type Order struct {
	BaseController
}

func (c *Order) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	status := c.GetString("status")
	t := c.GetString("type")
	c.Data["type"] = "0"
	ob := ` order by a.id desc`
	if status != "" {
		if status == "1" {
			ob = ` order by a.id desc`
		}
		w = append(w, `a.status=`+status)
		if t == "1" {
			c.Data["type"] = "1"
			w = append(w, `a.type=`+t)
		} else if status == "2" {
			w = append(w, `a.type=0`)
		}
	} else {
		w = append(w, `a.status>1 and a.status<6`)
	}
	c.Data["status"] = status
	search := c.GetString("search")
	c.Data["search"] = search
	id := c.GetString("id")
	c.Data["id"] = id
	if search != "" {
		w = append(w, `(a.ordernum like '%`+search+`%' or a.name like '%`+search+`%' or a.mobile like '%`+search+`%' or b.monicker like '%`+search+`%')`)
	}
	if c.Gid != "0" {
		w = append(w, `a.gid=`+c.Gid)
	} else {
		if id != "" {
			w = append(w, `a.gid=`+id)
		} else {
			w = append(w, `a.gid=0`)
		}
	}
	start := c.GetString("start")
	// beego.Debug(start)
	end := c.GetString("end")
	if start != "" && end != "" {
		if start == end {
			w = append(w, `a.addtime like '%`+start+`%'`)
		} else {
			w = append(w, `a.addtime > '`+start+`'`)
			w = append(w, `a.addtime < '`+end+`'`)
		}
	}
	c.Data["stime"] = start
	c.Data["etime"] = end
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num

	sql := `select a.*,c.pathname,b.monicker,d.name as shen,e.name as shi,f.name as qu from mt_order a left join mt_member b on a.uid=b.id 
	left join mt_resources c on b.avatar=c.id left join mt_area d on a.province=d.code left join mt_area e on a.city=e.code left join mt_area 
	f on a.area=f.code where d.pid=0 and e.pid>0 and ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_order a left join mt_member b on a.uid=b.id where ` + ws
	info := models.Query(sql)
	for _, i := range info {
		currentType := fmt.Sprint(i["type"])
		carid := fmt.Sprint(i["carid"])
		product := models.Query(`select a.*,b.id as pid,b.title,b.model,b.isw,b.length,b.height,b.width,b.weight,b.number,a.price as price,c.pathname,d.monicker
		 from mt_order_car a left join mt_product b on a.pid=b.id left join mt_resources c on b.img=c.id left join mt_member d
		  on a.did=d.id where a.id in(` + carid + `)`)
		var tj = "0.00"
		var zl = "0.00"
		for _, v := range product {
			// isw := fmt.Sprint(v["isw"])
			width := fmt.Sprint(v["width"])
			height := fmt.Sprint(v["height"])
			length := fmt.Sprint(v["length"])
			weight := fmt.Sprint(v["weight"])
			number := fmt.Sprint(v["number"])
			num := fmt.Sprint(v["num"])
			weight = sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
			v["weight"] = weight
			vtj := sword.Mult(length, sword.Mult(height, width))
			vtj = sword.Mult(vtj, num)
			v["tj"] = sword.Divi(vtj, "1000000")
			tj = sword.Sum(tj, vtj)
			zl = sword.Sum(zl, weight)
			// if isw == "0" {
			// } else {
			// }
			price := fmt.Sprint(v["price"])
			pprice := sword.Mult(number, price)
			v["pprice"] = pprice
			if status := fmt.Sprint(v["status"]); status == "3" || status == "4" {
				lostnum := sword.Cut(fmt.Sprint(v["num"]), fmt.Sprint(v["sendnum"]))
				if lostnum != "0.00" {
					pprice = sword.Mult(pprice, lostnum)
					v["rprice"] = pprice
				}
			}
		}
		i["tj"] = sword.Divi(tj, "1000000")
		i["zl"] = zl
		i["product"] = product
		if currentType == "1" {
			i["title"] = fmt.Sprint(product[0]["title"])
			i["num"] = product[0]["num"]
			i["pid"] = product[0]["pid"]
			tid := product[0]["tid"]
			gbuyTotals := models.Query(`select num from mt_active_gbuy where id=?`, tid)[0]["num"]
			i["gbuyTotals"] = gbuyTotals
			totals, _ := strconv.Atoi(gbuyTotals.(string))
			orders := models.Query(`select a.num from mt_order_car a 
				left join mt_order b on b.carid=a.id where a.tid=? and b.status>1 and b.status<6`, tid)
			gbuyNum := 0
			for _, v := range orders {
				i, _ := strconv.Atoi(v["num"].(string))
				gbuyNum += i
			}
			i["gbuyNum"] = gbuyNum
			if totals <= gbuyNum {
				i["satisfied"] = "1"
			}
		}
		rmoney := models.Query(`select sum(money) as money from mt_member_money_detail where type=7 and oid=?`, i["id"])[0]["money"]
		if rmoneys := fmt.Sprint(rmoney); rmoneys != "<nil>" {
			i["rmoney"] = rmoneys
			i["smoney"] = sword.Divi(fmt.Sprint(i["money"]), rmoneys)
		}

	}
	c.Data["driver"] = models.Query(`select a.id,a.monicker,b.pathname,c.name from mt_member a left join mt_resources b on a.avatar=b.id 
		left join mt_area c on a.driverarea=c.code where a.status=1 and a.driver=1`)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	gid := ""
	c.Data["url"] = `/admin/order/index?status=` + status + `&id=` + gid + `&search=` + search + `&start=` + start + `&end=` + end + `&`
	c.Data["urlc"] = `/admin/order/index?id=` + gid + `&search=` + search + `&start=` + start + `&end=` + end
	c.TplName = "admin/order/index.html"
}

type GbuyOrder struct {
	BaseController
}

func (c *GbuyOrder) Get() {
	gid := c.Gid
	var w []string
	w = append(w, `b.type=1 and a.status=2 and b.gid=`+gid)
	search := c.GetString("search")
	if search != "" {
		w = append(w, `(a.name like '%`+search+`%' or a.ordernum like '%`+search+`%' or a.mobile like '%`+search+`%' or c.monicker like '%`+search+`%')`)
	}
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc`
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	sql := `select a.*,b.num,c.monicker,d.pathname,e.name as sheng,f.name as shi,g.name as qv,p.width,p.length,p.height,p.weight,p.number  
		from mt_order a 
		left join mt_order_car b on a.carid=b.id 
		left join mt_product p on b.pid=p.id 
		left join mt_member c on c.id=a.uid 
		left join mt_resources d on d.id=c.avatar 
		left join mt_area e on e.code=a.province 
		left join mt_area f on f.code=a.city 
		left join mt_area g on g.code=a.area 
		where ` + ws + ob + lt
	info := models.Query(sql)
	for _, v := range info {
		width := fmt.Sprint(v["width"])
		height := fmt.Sprint(v["height"])
		length := fmt.Sprint(v["length"])
		weight := fmt.Sprint(v["weight"])
		number := fmt.Sprint(v["number"])
		num := fmt.Sprint(v["num"])
		weight = sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
		v["zl"] = weight
		vtj := sword.Mult(length, sword.Mult(height, width))
		vtj = sword.Mult(vtj, num)
		v["tj"] = sword.Divi(vtj, "1000000")
	}
	c.Data["paginator"] = models.Page(`select count(a.id) as totals from mt_order a 
		left join mt_order_car b on a.carid=b.id 
		left join mt_member c on c.id=a.uid 
		where `+ws, page2, num)
	c.Data["info"] = info
	c.Data["urlc"] = `/admin/order/index?`
	c.TplName = "admin/order/gbuy_index.html"
}

type OrderEdit struct {
	BaseController
}

func (c *OrderEdit) Get() {
	price := c.GetString("price")
	id := c.GetString("id")
	if c.Gid != "0" {
		if is := models.Query(`select id from mt_order where id=` + id + ` and gid=` + c.Gid); is != nil {
			if err := models.Exec(`update mt_order set money=` + price + ` where id=` + id); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
		} else {
			c.Ctx.Redirect(302, "/admin/order/index")
		}
	} else {
		if is := models.Query(`select id from mt_order where id=` + id); is != nil {
			if err := models.Exec(`update mt_order set money=` + price + ` where id=` + id); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
		} else {
			c.Ctx.Redirect(302, "/admin/order/index")
		}
	}
	c.ServeJSON()
	var r models.Mt_systems_record
	r.Tid, _ = strconv.Atoi(id)
	r.Way = 3
	r.Addtime = sword.Timeget()
	r.Table = 18
	r.Uid, _ = strconv.Atoi(c.Qid)
	if _, err := models.Orm().Insert(&r); err != nil {
		beego.Debug(err)
	}
}

type OrderContent struct {
	BaseController
}

func (c *OrderContent) Get() {
	c.Data["driver"] = models.Query(`select a.id,a.monicker,b.pathname,c.name from mt_member a left join mt_resources b on a.avatar=b.id 
		left join mt_area c on a.driverarea=c.code where a.status=1 and a.driver=1`)
	id := c.GetString("id")
	if c.Gid != "0" {
		if is := models.Query(`select id from mt_order where id=` + id + ` and gid=` + c.Gid); is == nil {
			c.Ctx.Redirect(302, "/admin/order/index")
		}
	} else {
		if is := models.Query(`select id from mt_order where id=` + id); is == nil {
			c.Ctx.Redirect(302, "/admin/order/index")
		}
	}
	order := models.Query(`select a.*,a.uid as uid,b.monicker,b.uid as puid,c.pathname,d.pathname as spathname,e.name as gname,i.name as shen,
		o.name as shi,p.name as qu from mt_order a left join mt_member b on a.uid=b.id left join mt_resources c on b.avatar=c.id
		 left join mt_resources d on a.sendimg=d.id left join mt_shop e on a.gid=e.id left join mt_area i on a.province=i.code 
		 left join mt_area o on a.city=o.code left join mt_area p on a.area=p.code where a.id=` + id)[0]
	carid := fmt.Sprint(order["carid"])
	product := models.Query(`select a.*,b.title,b.model,b.isw,b.length,b.height,b.width,b.weight,b.number,a.price as price,c.pathname,d.monicker
		 from mt_order_car a left join mt_product b on a.pid=b.id left join mt_resources c on b.img=c.id left join mt_member d
		  on a.did=d.id where a.id in(` + carid + `)`)
	var tj = "0.00"
	var zl = "0.00"
	var totalFoldPrice = "0.00"
	var totalNum = 0
	for _, v := range product {
		// isw := fmt.Sprint(v["isw"])
		width := fmt.Sprint(v["width"])
		height := fmt.Sprint(v["height"])
		length := fmt.Sprint(v["length"])
		weight := fmt.Sprint(v["weight"])
		number := fmt.Sprint(v["number"])
		num := fmt.Sprint(v["num"])
		numInt, _ := strconv.Atoi(num)
		totalNum += numInt
		brandFold := fmt.Sprint(v["brandFold"])
		weight = sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
		v["weight"] = weight
		vtj := sword.Mult(length, sword.Mult(height, width))
		vtj = sword.Mult(vtj, num)
		v["tj"] = sword.Divi(vtj, "1000000")
		tj = sword.Sum(tj, vtj)
		zl = sword.Sum(zl, weight)
		price := fmt.Sprint(v["price"])
		pprice := sword.Mult(number, price)
		v["pprice"] = pprice
		v["ppriceall"] = sword.Mult(pprice, num)
		if brandFold != "100" {
			fprice := sword.Divi(sword.Mult(v["price"].(string), brandFold), "100")
			v["brandFoldPriceCell"] = sword.Mult(fprice, number)
			fprice = sword.Cut(price, fprice)
			totalPrice := sword.Mult(sword.Mult(fprice, number), num)
			totalFoldPrice = sword.Sum(totalPrice, totalFoldPrice)
		}
		if status := fmt.Sprint(v["status"]); status == "3" || status == "4" {
			lostnum := sword.Cut(fmt.Sprint(v["num"]), fmt.Sprint(v["sendnum"]))
			if lostnum != "0.00" {
				pprice = sword.Mult(pprice, lostnum)
				v["rprice"] = pprice
			}
		}
	}
	order["tj"] = sword.Divi(tj, "1000000")
	order["zl"] = zl
	order["totalFoldPrice"] = totalFoldPrice
	order["totalNum"] = totalNum
	c.Data["info"] = order
	c.Data["product"] = product
	if yid := fmt.Sprint(order["yid"]); yid != "0" {
		c.Data["coupon"] = models.Query(`select b.name,b.offer from mt_member_coupon a left join mt_coupon b on a.yid=b.id where a.id=` + yid)[0]
	}
	if puid := fmt.Sprint(order["puid"]); puid != "0" && fmt.Sprint(order["commission"]) != "0.00" {
		if pmem := models.Query(`select a.monicker,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + puid); pmem != nil {
			c.Data["pmem"] = pmem[0]
		}
	}
	c.TplName = "admin/order/content.html"
}

type OrderSend struct {
	BaseController
}

func (c *OrderSend) Get() {
	c.TplName = "admin/order/send.html"
}
func (c *OrderSend) Post() {
	id := c.GetString("id")
	drivername := c.GetString("drivername")
	drivermobile := c.GetString("drivermobile")
	sendimg := c.GetString("sendimg")
	var sql string
	if c.Gid != "0" {
		sql = `select id,uid from mt_order where status=2 and id=` + id
	} else {
		sql = `select id,uid from mt_order where status=2 and id=` + id + ` and gid=` + c.Gid
	}
	if is := models.Query(sql); is != nil {
		if err := models.Exec(fmt.Sprintf(`update mt_order set status=3,shippingtime='%v',drivername='%v',drivermobile='%v',sendimg='%v' where id=%v`,
			sword.Gettimes(""), drivername, drivermobile, sendimg, id)); err != nil {
			c.Data["json"] = 0
			beego.Debug(err)
		} else {
			c.Data["json"] = 1
		}
	} else {
		c.Data["json"] = 0
	}
	c.ServeJSON()
}

type OrderDriver struct {
	BaseController
}

func (c *OrderDriver) Get() {
	if err := models.Exec(`update mt_order_car set did=` + c.GetString("did") + ` where id=` + c.GetString("id")); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
	c.ServeJSON()
}

type OrderReturnOutofstock struct {
	BaseController
}

func (c *OrderReturnOutofstock) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	oid := c.GetString("oid")
	rprice := c.GetString("rprice")
	uid := models.Query(`select uid from mt_order_car where id=` + id)[0]["uid"].(string)
	money_detail := models.Query(`select * from mt_member_money_detail where oid=` + oid + ` and type=3`)[0]
	ptype := fmt.Sprint(money_detail["paytype"])
	o := models.Orm()
	o.Begin()
	if _, err := o.Raw("update mt_order_car set `return`=1 where id=" + id).Exec(); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		o.Rollback()
		return
	}
	switch ptype {
	case "1":
		if _, err := o.Raw(`update mt_member set money=money+` + rprice + ` where id=` + uid).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		}
		if _, err := o.Raw(fmt.Sprintf("insert into mt_member_money_detail (uid,type,money,oid,`return`,addtime) "+
			"values ('%v','%v','%v','%v','%v','%v')", uid, 6, rprice, oid, 1, sword.Gettimes(""))).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		}
		c.Data["json"] = 1
		o.Commit()
	case "2":
		if err := mobile.WxRefund(money_detail["id"].(string), rprice); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		} else {
			c.Data["json"] = 1
			o.Commit()
		}
	case "3":
		if err := mobile.AlipayRefund(money_detail["id"].(string), rprice); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		} else {
			c.Data["json"] = 1
			o.Commit()
		}
	}
}

type OrderReturn struct {
	BaseController
}

func (c *OrderReturn) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	agree := c.GetString("agree")
	c.Data["agree"] = agree
	if agree != "" {
		w = append(w, `a.agree=`+agree)
	}
	check := c.GetString("check")
	c.Data["check"] = check
	if check != "" {
		w = append(w, `a.check=`+check)
	}
	if c.Gid != "0" {
		w = append(w, `d.gid=`+c.Gid)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	sql := `select a.*,c.pathname,b.monicker,d.ordernum,d.money,e.name as whys,d.carid from mt_order_return a join mt_order d on a.oid=d.id 
	left join mt_member b on d.uid=b.id left join mt_resources c on b.avatar=c.id left join mt_systems_configuration e on a.why=e.id
	 where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_order_return a join mt_order d on a.oid=d.id where ` + ws
	info := models.Query(sql)
	for _, v := range info {
		oid := fmt.Sprint(v["oid"])
		returnmoney := models.Query(`select sum(money) as rmoney from mt_member_money_detail where type=6 and oid=` + oid)[0]["rmoney"]
		var rmoney string
		if returnmoney == nil {
			rmoney = `0.00`
		} else {
			rmoney = returnmoney.(string)
		}
		v["rmoney"] = rmoney
		carid := fmt.Sprint(v["carid"])

		product := models.Query(`select a.*,b.title,b.model,b.isw,b.length,b.height,b.width,b.weight,b.number,a.price as price,c.pathname,d.monicker
		 from mt_order_car a left join mt_product b on a.pid=b.id left join mt_resources c on b.img=c.id left join mt_member d
		  on a.did=d.id where a.id in(` + carid + `)`)
		var tj = "0.00"
		var zl = "0.00"
		for _, v := range product {
			// isw := fmt.Sprint(v["isw"])
			width := fmt.Sprint(v["width"])
			height := fmt.Sprint(v["height"])
			length := fmt.Sprint(v["length"])
			weight := fmt.Sprint(v["weight"])
			number := fmt.Sprint(v["number"])
			num := fmt.Sprint(v["num"])
			weight = sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
			v["weight"] = weight
			vtj := sword.Mult(length, sword.Mult(height, width))
			vtj = sword.Mult(vtj, num)
			v["tj"] = sword.Divi(vtj, "1000000")
			tj = sword.Sum(tj, vtj)
			zl = sword.Sum(zl, weight)
			// if isw == "0" {
			// } else {
			// }
			price := fmt.Sprint(v["price"])
			pprice := sword.Mult(number, price)
			v["pprice"] = pprice
			if status := fmt.Sprint(v["status"]); status == "3" || status == "4" {
				lostnum := sword.Cut(fmt.Sprint(v["num"]), fmt.Sprint(v["sendnum"]))
				if lostnum != "0.00" {
					pprice = sword.Mult(pprice, lostnum)
					v["rprice"] = pprice
				}
			}
		}
		v["tj"] = sword.Divi(tj, "1000000")
		v["zl"] = zl
		v["product"] = product
	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["urlc"] = `/admin/order/return`
	c.TplName = "admin/order/return.html"
}

type OrderReturnAgree struct {
	BaseController
}

func (c *OrderReturnAgree) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	agree := c.GetString("agree")
	if err := models.Exec(`update mt_order_return set agree=` + agree + ` where id=` + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
}

type OrderReturnCheck struct {
	BaseController
}

func (c *OrderReturnCheck) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	check := c.GetString("check")
	if err := models.Exec("update mt_order_return set `check`=" + check + " where id=" + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
}

type OrderReturnMoney struct {
	BaseController
}

func (c *OrderReturnMoney) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	re := models.Query(`select a.returnmoney,a.oid,b.uid from mt_order_return a left join mt_order b on a.oid=b.id 
		where a.agree=1 and a.check=1 and a.return=0 and a.id=` + id)
	if re == nil {
		c.Data["json"] = 0
		return
	}
	money := c.GetString("money")
	oid := fmt.Sprint(re[0]["oid"])
	uid := fmt.Sprint(re[0]["uid"])
	nowtimes := sword.Gettimes("")
	money_detail := models.Query(`select * from mt_member_money_detail where oid=` + oid + ` and type=3`)[0]
	o := models.Orm()
	o.Begin()
	if _, err := o.Raw("update mt_order_return set `return`=1,returntime='" + nowtimes + "' where id=" + id).Exec(); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		o.Rollback()
		return
	}
	ptype := fmt.Sprint(money_detail["paytype"])
	switch ptype {
	case "1":
		if _, err := o.Raw(`update mt_member set money=money+` + money + ` where id=` + uid).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		}
		if _, err := o.Raw(fmt.Sprintf("insert into mt_member_money_detail (uid,type,money,oid,`return`,addtime) "+
			"values ('%v','%v','%v','%v','%v','%v')", uid, 6, money, oid, 1, nowtimes)).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		}
		c.Data["json"] = 1
		o.Commit()
	case "2":
		if err := mobile.WxRefund(money_detail["id"].(string), money); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		} else {
			c.Data["json"] = 1
			o.Commit()
		}
	case "3":
		if err := mobile.AlipayRefund(money_detail["id"].(string), money); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		} else {
			c.Data["json"] = 1
			o.Commit()
		}
	}
}

type OrderShopcarDel struct {
	BaseController
}

func (c *OrderShopcarDel) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	oid := c.GetString("oid")
	beego.Debug(id)
	beego.Debug(oid)
	order := models.Query(`select carid,count,tax,yid,invoice,gid from mt_order where id=?`, oid)[0]
	carid := fmt.Sprint(order["carid"])
	carids := strings.Split(carid, ",")
	var newcarid []string
	for _, v := range carids {
		if v != id {
			newcarid = append(newcarid, v)
		}
	}
	beego.Debug(newcarid)
	if len(newcarid) == 0 {
		if err := models.Exec(`update mt_order set status=0 where id=?`, oid); err != nil {
			beego.Debug(err)
		}
		c.Data["json"] = 2
		return
	}

	var pricem = "0.00"
	var moneym = "0.00"
	newcarids := strings.Join(newcarid, ",")
	shopcar := models.Query(`select a.id,a.num,a.pid,a.price as cprice,b.price,b.number,a.type,a.gid,b.isvip,a.spec from mt_order_car a left join mt_product b on a.pid=b.id 
		where a.id in(` + newcarids + `)`)
	for _, s := range shopcar {
		price := fmt.Sprint(s["cprice"])
		price2 := fmt.Sprint(s["price"])
		number := fmt.Sprint(s["number"])
		num := fmt.Sprint(s["num"])
		if fmt.Sprint(s["spec"]) == "0" {
			pricem = sword.Sum(pricem, sword.Mult(price2, sword.Mult(number, num)))
			moneym = sword.Sum(moneym, sword.Mult(price, sword.Mult(number, num)))
		} else {
			pricem = sword.Sum(pricem, sword.Mult(price2, num))
			moneym = sword.Sum(moneym, sword.Mult(price, num))
		}
	}
	count := sword.Cut(pricem, moneym)
	yid := fmt.Sprint(order["yid"])
	if yid != "0" {
		coupon := models.Query(`select b.offer from mt_member_coupon a left join mt_coupon b on a.yid=b.id where a.id=` + yid)[0]
		c_count := fmt.Sprint(coupon["offer"])
		moneym = sword.Cut(moneym, c_count)
	}

	invoice := fmt.Sprint(order["invoice"])
	gid := fmt.Sprint(order["gid"])
	var taxmoney = "0"
	if invoice == "1" {
		var tax = "0"
		if gid == "0" {
			tax = fmt.Sprint(models.Systems()["taxpoint"])
		} else {
			tax = fmt.Sprint(models.Query(`select taxpoint from mt_shop where id=` + gid))
		}
		// tax := models.Systems()["taxpoint"].(string)
		taxmoney = sword.Divi(sword.Mult(moneym, tax), "100")
		moneym = sword.Sum(moneym, taxmoney)
	}
	if err := models.Exec(`
		update mt_order 
		set carid=?,price=?,money=?,count=?,tax=? 
		where id=?`, newcarids, pricem, moneym, count, taxmoney, oid); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		return
	}
	c.Data["json"] = 1
	var r models.Mt_systems_record
	r.Tid, _ = strconv.Atoi(oid)
	r.Way = 3
	r.Addtime = sword.Timeget()
	r.Table = 18
	r.Uid, _ = strconv.Atoi(c.Qid)
	if _, err := models.Orm().Insert(&r); err != nil {
		beego.Debug(err)
	}
}

type OrderShopcarChange struct {
	BaseController
}

func (c *OrderShopcarChange) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	oid := c.GetString("oid")
	num := c.GetString("num")
	order := models.Query(`select carid,count,tax,yid,invoice,gid from mt_order where id=?`, oid)[0]
	if err := models.Exec(`update mt_order_car set num=? where id=?`, num, id); err != nil {
		c.Data["json"] = 0
		return
	}

	var pricem = "0.00"
	var moneym = "0.00"
	newcarids := fmt.Sprint(order["carid"])
	shopcar := models.Query(`select a.id,a.num,a.pid,a.price as cprice,b.price,b.number,a.type,a.gid,b.isvip,a.spec from mt_order_car a left join mt_product b on a.pid=b.id 
		where a.id in(` + newcarids + `)`)
	for _, s := range shopcar {
		price := fmt.Sprint(s["cprice"])
		price2 := fmt.Sprint(s["price"])
		number := fmt.Sprint(s["number"])
		num := fmt.Sprint(s["num"])
		if fmt.Sprint(s["spec"]) == "0" {
			pricem = sword.Sum(pricem, sword.Mult(price2, sword.Mult(number, num)))
			moneym = sword.Sum(moneym, sword.Mult(price, sword.Mult(number, num)))
		} else {
			pricem = sword.Sum(pricem, sword.Mult(price2, num))
			moneym = sword.Sum(moneym, sword.Mult(price, num))
		}
	}
	count := sword.Cut(pricem, moneym)
	yid := fmt.Sprint(order["yid"])
	if yid != "0" {
		coupon := models.Query(`select b.offer from mt_member_coupon a left join mt_coupon b on a.yid=b.id where a.id=` + yid)[0]
		c_count := fmt.Sprint(coupon["offer"])
		moneym = sword.Cut(moneym, c_count)
	}

	invoice := fmt.Sprint(order["invoice"])
	gid := fmt.Sprint(order["gid"])
	var taxmoney = "0"
	if invoice == "1" {
		var tax = "0"
		if gid == "0" {
			tax = fmt.Sprint(models.Systems()["taxpoint"])
		} else {
			tax = fmt.Sprint(models.Query(`select taxpoint from mt_shop where id=` + gid))
		}
		// tax := models.Systems()["taxpoint"].(string)
		taxmoney = sword.Divi(sword.Mult(moneym, tax), "100")
		moneym = sword.Sum(moneym, taxmoney)
	}
	if err := models.Exec(`
		update mt_order 
		set price=?,money=?,count=?,tax=? 
		where id=?`, pricem, moneym, count, taxmoney, oid); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		return
	}
	c.Data["json"] = 1
	var r models.Mt_systems_record
	r.Tid, _ = strconv.Atoi(oid)
	r.Way = 3
	r.Addtime = sword.Timeget()
	r.Table = 18
	r.Uid, _ = strconv.Atoi(c.Qid)
	if _, err := models.Orm().Insert(&r); err != nil {
		beego.Debug(err)
	}
}

type OrderShopcarAdd struct {
	BaseController
}

func (c *OrderShopcarAdd) Get() {
	beego.Debug(c.Input())

	uid, _ := c.GetInt("uid")
	oid, _ := c.GetInt("oid")
	num, _ := c.GetInt("num")
	pid, _ := c.GetInt("pid")

	defer c.ServeJSON()

	if uid == 0 {
		c.Data["json"] = 2
		return
	}

	if oid == 0 {
		c.Data["json"] = 2
		return
	}

	if num == 0 {
		c.Data["json"] = 2
		return
	}

	if pid == 0 {
		c.Data["json"] = 2
		return
	}
	order := models.Query(`select carid,count,tax,yid,invoice,gid from mt_order where id=?`, oid)[0]
	newcarids := fmt.Sprint(order["carid"])
	beego.Debug(newcarids)
	o := models.Orm()
	o.Begin()
	if ishave := models.Query(`select id from mt_order_car where pid=? and uid=? and status=1 and type in(0,2) and spec=0 and id in(`+newcarids+`)`, pid, uid); ishave != nil {
		if _, err := o.Raw(`update mt_order_car set num=num+? where id=?`, num, ishave[0]["id"].(string)).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		}
		beego.Debug(1)
	} else {

		price, gid, tid := mobile.ProductPrice(fmt.Sprint(pid), fmt.Sprint(uid))
		sql := fmt.Sprintf(`insert into mt_order_car (pid,gid,num,uid,price,addtime,spec,type,status) values (%v,%v,%v,%v,%v,'%v',%v,%v,2)`,
			pid, gid, num, uid, price, sword.Gettimes(""), 0, tid)
		if ret, err := models.Orm().Raw(sql).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
			return
		} else {
			rid, _ := ret.LastInsertId()
			newcarids += "," + fmt.Sprint(rid)
		}
		beego.Debug(2)
		beego.Debug(newcarids)
	}

	var pricem = "0.00"
	var moneym = "0.00"
	shopcar := models.Query(`select a.id,a.num,a.pid,a.price as cprice,b.price,b.number,a.type,a.gid,b.isvip,a.spec from mt_order_car a left join mt_product b on a.pid=b.id 
		where a.id in(` + newcarids + `)`)
	for _, s := range shopcar {
		price := fmt.Sprint(s["cprice"])
		price2 := fmt.Sprint(s["price"])
		number := fmt.Sprint(s["number"])
		num := fmt.Sprint(s["num"])
		if fmt.Sprint(s["spec"]) == "0" {
			pricem = sword.Sum(pricem, sword.Mult(price2, sword.Mult(number, num)))
			moneym = sword.Sum(moneym, sword.Mult(price, sword.Mult(number, num)))
		} else {
			pricem = sword.Sum(pricem, sword.Mult(price2, num))
			moneym = sword.Sum(moneym, sword.Mult(price, num))
		}
	}
	count := sword.Cut(pricem, moneym)
	yid := fmt.Sprint(order["yid"])
	if yid != "0" {
		coupon := models.Query(`select b.offer from mt_member_coupon a left join mt_coupon b on a.yid=b.id where a.id=` + yid)[0]
		c_count := fmt.Sprint(coupon["offer"])
		moneym = sword.Cut(moneym, c_count)
	}

	invoice := fmt.Sprint(order["invoice"])
	gid := fmt.Sprint(order["gid"])
	var taxmoney = "0"
	if invoice == "1" {
		var tax = "0"
		if gid == "0" {
			tax = fmt.Sprint(models.Systems()["taxpoint"])
		} else {
			tax = fmt.Sprint(models.Query(`select taxpoint from mt_shop where id=` + gid))
		}
		// tax := models.Systems()["taxpoint"].(string)
		taxmoney = sword.Divi(sword.Mult(moneym, tax), "100")
		moneym = sword.Sum(moneym, taxmoney)
	}
	if _, err := o.Raw(`
		update mt_order 
		set price=?,money=?,count=?,tax=?,carid=? 
		where id=?`, pricem, moneym, count, taxmoney, newcarids, oid).Exec(); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		o.Rollback()
		return
	}
	o.Commit()
	c.Data["json"] = 1
	var r models.Mt_systems_record
	r.Tid = oid
	r.Way = 3
	r.Addtime = sword.Timeget()
	r.Table = 18
	r.Uid, _ = strconv.Atoi(c.Qid)
	if _, err := models.Orm().Insert(&r); err != nil {
		beego.Debug(err)
	}
}

type OrderStatistics struct {
	BaseController
}

func (c *OrderStatistics) Get() {
	status := c.GetString("status")
	stime := c.GetString("stime")
	etime := c.GetString("etime")
	search := c.GetString("search")

	c.Data["status"] = status
	c.Data["stime"] = stime
	c.Data["etime"] = etime
	c.Data["search"] = search

	var w []string
	w = append(w, `a.gid=`+c.Gid)

	if status == "" {
		w = append(w, `a.status>0 and a.status<6`)
	} else if status == "1" {
		w = append(w, `a.status=1`)
	} else if status == "2" {
		w = append(w, `a.status>1 and a.status<6`)
	}

	if stime != "" {
		w = append(w, `a.addtime>'`+stime+` 00:00:00'`)
	}

	if etime != "" {
		w = append(w, `a.addtime<='`+etime+` 00:00:00'`)
	}

	if search != "" {
		w = append(w, `(a.ordernum like '%`+search+`%' or a.mobile like '%`+search+`%')`)
	}

	ws := strings.Join(w, ` and `)
	page, page2, num := models.Pagechange(c.GetString("page"), "20")
	lt := ` limit ` + page + `,` + num

	ob := ` order by a.addtime desc `

	info := models.Query(`
		select a.id,a.money,a.ordernum,a.status,b.monicker 
		from mt_order a 
		left join mt_member b on a.uid=b.id 
		where ` + ws + ob + lt)
	c.Data["info"] = info
	sql2 := `select count(a.id) as totals from mt_order a where ` + ws

	c.Data["paginator"] = models.Page(sql2, page2, num)

	c.Data["url"] = `/admin/order/statistics?status=` + status + `&stime=` + stime + `&search=` + search + `&etime=` + etime + `&`

	c.Data["money"] = models.Query(`select sum(a.money) as moneys from mt_order a where ` + ws)[0]["moneys"]
	c.Data["count"] = models.Query(`select count(a.id) as count from mt_order a where ` + ws)[0]["count"]

	c.TplName = "admin/order/statistics.html"
}

type OrderExcel struct {
	BaseController
}

func (c *OrderExcel) Get() {
	id := c.GetString("id")
	info := models.Query(`select ordernum,carid from mt_order where id=?`, id)
	if info == nil {
		return
	}
	xlsx := excelize.NewFile()
	// index := xlsx.NewSheet("Sheet1")

	xlsx.SetCellValue("Sheet1", "A1", "产品名称")
	xlsx.SetCellValue("Sheet1", "B1", "条形码")
	xlsx.SetCellValue("Sheet1", "C1", "产品规格")
	xlsx.SetCellValue("Sheet1", "D1", "体积(立方)")
	xlsx.SetCellValue("Sheet1", "E1", "装箱数")
	xlsx.SetCellValue("Sheet1", "F1", "会员价")
	xlsx.SetCellValue("Sheet1", "G1", "零售价")
	xlsx.SetCellValue("Sheet1", "H1", "数量")
	// xlsx.SetCellValue("Sheet1", "I1", "总价")
	shopcar := models.Query(`select a.gid,a.pid,a.num,a.sendnum,a.status,b.title,b.spec,b.number,b.barcode,a.price,c.pathname,b.model,a.spec as spec2,b.width,b.length,b.height,b.weight,b.price as retailPrice   
			from mt_order_car a 
			left join mt_product b on a.pid=b.id 
			left join mt_resources c on b.img=c.id 
			where a.id in(` + fmt.Sprint(info[0]["carid"]) + `)`)

	for k, v := range shopcar {
		k += 2
		xlsx.SetCellValue("Sheet1", "F"+fmt.Sprint(k), v["price"])
		if fmt.Sprint(v["spec2"]) == "0" {
			v["price"] = sword.Mult(v["price"].(string), v["number"].(string))
		}
		width := fmt.Sprint(v["width"])
		length := fmt.Sprint(v["length"])
		height := fmt.Sprint(v["height"])
		// weight := fmt.Sprint(v["weight"])
		// number := fmt.Sprint(v["number"])
		num := fmt.Sprint(v["num"])

		tjone := sword.Divi(sword.Mult(width, sword.Mult(height, sword.Mult(length, num))), "1000000")
		// zlone := sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
		xlsx.SetCellValue("Sheet1", "A"+fmt.Sprint(k), v["title"])
		xlsx.SetCellValue("Sheet1", "B"+fmt.Sprint(k), v["barcode"])
		xlsx.SetCellValue("Sheet1", "C"+fmt.Sprint(k), v["spec"])
		xlsx.SetCellValue("Sheet1", "D"+fmt.Sprint(k), tjone)
		xlsx.SetCellValue("Sheet1", "E"+fmt.Sprint(k), v["number"])
		xlsx.SetCellValue("Sheet1", "G"+fmt.Sprint(k), v["retailPrice"])
		xlsx.SetCellValue("Sheet1", "H"+fmt.Sprint(k), num)
		// xlsx.SetCellValue("Sheet1", "I"+fmt.Sprint(k), sword.Mult(num, fmt.Sprint(v["price"])))
	}

	// nowtimes := fmt.Sprint(time.Now().Unix())
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	ordernum := fmt.Sprint(info[0]["ordernum"])
	err = xlsx.SaveAs("static/xlsx/" + ordernum + ".xlsx")
	if err != nil {
		beego.Debug(err)
		return
	}
	c.Ctx.Redirect(302, "/static/xlsx/"+ordernum+".xlsx")
}

type OrdersExcel struct {
	BaseController
}

func (c *OrdersExcel) Get() {
	status := c.GetString("status")
	var w []string
	if status == "" {
		w = append(w, `a.status>0 and a.status<6`)
	} else {
		w = append(w, `a.status=`+status)
	}
	search := c.GetString("search")
	if search != "" {
		w = append(w, `(a.ordernum like '%`+search+`%' or a.name like '%`+search+`%' or a.mobile like '%`+search+`%' or b.monicker like '%`+search+`%')`)
	}
	start := c.GetString("start")
	// beego.Debug(start)
	end := c.GetString("end")
	if start != "" && end != "" {
		if start == end {
			w = append(w, `a.addtime like '%`+start+`%'`)
		} else {
			w = append(w, `a.addtime > '`+start+`'`)
			w = append(w, `a.addtime < '`+end+`'`)
		}
	}
	w = append(w, `a.gid=`+c.Gid)
	ws := strings.Join(w, ` and `)
	sql := `select a.*,c.pathname,b.monicker,d.name as shen,e.name as shi,f.name as qu from mt_order a left join mt_member b on a.uid=b.id 
	left join mt_resources c on b.avatar=c.id left join mt_area d on a.province=d.code left join mt_area e on a.city=e.code left join mt_area 
	f on a.area=f.code where d.pid=0 and e.pid>0 and ` + ws
	orders := models.Query(sql)
	if orders == nil {
		beego.Debug("无订单")
	}
	xlsx := excelize.NewFile()
	xlsx.SetCellValue("Sheet1", "A1", "产品名称")
	xlsx.SetCellValue("Sheet1", "B1", "条形码")
	xlsx.SetCellValue("Sheet1", "C1", "产品型号")
	xlsx.SetCellValue("Sheet1", "D1", "装箱数")
	xlsx.SetCellValue("Sheet1", "E1", "体积(立方)")
	xlsx.SetCellValue("Sheet1", "F1", "重量(kg)")
	xlsx.SetCellValue("Sheet1", "G1", "数量")
	xlsx.SetCellValue("Sheet1", "H1", "单价")
	xlsx.SetCellValue("Sheet1", "I1", "总价")
	xlsx.SetCellValue("Sheet1", "J1", "订单号")
	xlsx.SetCellValue("Sheet1", "K1", "订单状态")
	xlsx.SetCellValue("Sheet1", "L1", "订单添加时间")
	xlsx.SetCellValue("Sheet1", "M1", "订单付款时间")
	xlsx.SetCellValue("Sheet1", "N1", "所属客户")
	k := 1
	for _, v := range orders {
		ordernum := v["ordernum"].(string)
		var status string
		switch v["status"].(string) {
		case "1":
			status = "带付款"
		case "2":
			status = "待发货"
		case "3":
			status = "待收货"
		case "4":
			status = "待评价"
		case "5":
			status = "已完成"
		}
		shopcar := models.Query(`select d.monicker as customer_name,a.gid,a.pid,a.num,a.sendnum,a.status,a.addtime,a.paytime,b.title,b.spec,b.number,b.barcode,a.price,c.pathname,b.model,a.spec as spec2,b.width,b.length,b.height,b.weight  
			from mt_order_car a 
			left join mt_product b on a.pid=b.id 
			left join mt_resources c on b.img=c.id 
			left join  mt_member d on a.uid=d.id
			where a.id in(` + v["carid"].(string) + `)`)

		for _, v := range shopcar {
			k += 1
			xlsx.SetCellValue("Sheet1", "H"+fmt.Sprint(k), v["price"])
			if fmt.Sprint(v["spec2"]) == "0" {
				v["price"] = sword.Mult(v["price"].(string), v["number"].(string))
			}
			width := fmt.Sprint(v["width"])
			length := fmt.Sprint(v["length"])
			height := fmt.Sprint(v["height"])
			weight := fmt.Sprint(v["weight"])
			number := fmt.Sprint(v["number"])
			num := fmt.Sprint(v["num"])

			tjone := sword.Divi(sword.Mult(width, sword.Mult(height, sword.Mult(length, num))), "1000000")
			zlone := sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
			xlsx.SetCellValue("Sheet1", "A"+fmt.Sprint(k), v["title"])
			xlsx.SetCellValue("Sheet1", "B"+fmt.Sprint(k), v["barcode"])
			xlsx.SetCellValue("Sheet1", "C"+fmt.Sprint(k), v["model"])
			xlsx.SetCellValue("Sheet1", "D"+fmt.Sprint(k), v["number"])
			xlsx.SetCellValue("Sheet1", "E"+fmt.Sprint(k), tjone)
			xlsx.SetCellValue("Sheet1", "F"+fmt.Sprint(k), zlone)
			xlsx.SetCellValue("Sheet1", "G"+fmt.Sprint(k), num)
			xlsx.SetCellValue("Sheet1", "I"+fmt.Sprint(k), sword.Mult(num, fmt.Sprint(v["price"])))
			xlsx.SetCellValue("sheet1", "J"+fmt.Sprint(k), ordernum)
			xlsx.SetCellValue("Sheet1", "K"+fmt.Sprint(k), status)
			xlsx.SetCellValue("Sheet1", "L"+fmt.Sprint(k), v["addtime"])
			xlsx.SetCellValue("Sheet1", "M"+fmt.Sprint(k), v["paytime"])
			xlsx.SetCellValue("Sheet1", "N"+fmt.Sprint(k), v["customer_name"])
		}
	}
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	filename := "orders"
	err = xlsx.SaveAs("static/xlsx/" + filename + ".xlsx")
	if err != nil {
		beego.Debug(err)
		return
	}
	c.Ctx.Redirect(302, "/static/xlsx/"+filename+".xlsx")
}

type Finance struct {
	BaseController
}

func (c *Finance) Get() {
	c.TplName = "admin/order/finance.html"
}

type OrderExportImg struct {
	BaseController
}

func (c *OrderExportImg) Get() {
	defer c.ServeJSON()
	json := make(map[string]interface{})
	c.Data["json"] = &json
	orderId := c.GetString("id")
	order := models.Query(`select carid from mt_order where id=?`, orderId)
	if order == nil {
		beego.Debug("未找到相关订单id:" + orderId)
		json["msg"] = "未找到相关订单id:" + orderId
		json["status"] = 0
		return
	}
	orderCar := models.Query(`select a.id,a.title,a.img,a.image from mt_product a 
		join (select pid from mt_order_car 
			where id in(` + order[0]["carid"].(string) + `)) b on b.pid=a.id`)
	if order == nil {
		beego.Debug("未找到相关订单id:" + orderId + "的产品")
		json["msg"] = "未找到相关订单id:" + orderId + "的产品"
		json["status"] = 0
		return
	}
	if mkdirErr := os.MkdirAll("static/orderimg", 0777); mkdirErr != nil {
		beego.Debug(mkdirErr)
		json["status"] = 0
		return
	}
	zipName := "static/orderimg/img(" + orderId + ").zip"
	file, fileErr := os.Create(zipName)
	defer os.RemoveAll(zipName)
	if fileErr != nil {
		beego.Debug(fileErr)
		json["status"] = 0
		return
	}
	zw := zip.NewWriter(file)
	defer zw.Close()
	for _, o := range orderCar {
		// reg, _ := regexp.Compile("\\d*$")
		// productTitle := reg.FindString(o["title"].(string))
		// beego.Debug(productTitle)
		pics := ""
		if o["img"] != nil {
			pics += o["img"].(string)
		}
		if o["image"] != nil {
			pics += "," + o["image"].(string)
		}
		if pics == "" {
			beego.Debug(o["title"].(string) + `没有图片`)
			json["msg"] = o["title"].(string) + `没有图片`
			json["status"] = 0
			return
		}
		pathname := models.Query(`select pathname from mt_resources where id in(` + pics + `)`)
		for i, v := range pathname {
			pathname := v["pathname"].(string)
			pathname = strings.TrimLeft(pathname, "/")
			imgFile, fileErr := os.Open(pathname)
			if fileErr != nil {
				beego.Debug(fileErr)
				json["status"] = 0
				return
			}
			defer imgFile.Close()
			fileInfo, fileErr := imgFile.Stat()
			if fileErr != nil {
				beego.Debug(fileErr)
				json["status"] = 0
				return
			}
			InfoHeader, fileErr := zip.FileInfoHeader(fileInfo)
			if fileErr != nil {
				beego.Debug(fileErr)
				json["status"] = 0
				return
			}
			ext := strings.ToLower(path.Ext(pathname))
			InfoHeader.Name = o["title"].(string) + "(" + strconv.Itoa(i) + ")" + ext
			fileWriter, fileErr := zw.CreateHeader(InfoHeader)
			if fileErr != nil {
				beego.Debug(fileErr)
				json["status"] = 0
				return
			}
			io.Copy(fileWriter, imgFile)

		}
	}
	json["filePath"] = zipName
	json["status"] = 1
}

type OrderInterface struct {
	beego.Controller
}

func (c *OrderInterface) Get() {
	defer c.ServeJSON()
	json := make(map[string]interface{})
	c.Data["json"] = &json
	p := c.GetString("p")
	t := c.GetString("type")
	stime := c.GetString("stime")
	etime := c.GetString("etime")
	ordernums := c.GetString("ordernums")
	// nowTime := time.Now()
	// time := nowTime.Add(-time.Minute * 30).Local().Format("2006-01-02 15:04-05")
	if p != "a43d2227fd18423a2049b417dfa46e98" {
		json["msg"] = "无订单"
		json["status"] = 0
		return
	}
	orderCar := models.Query(`select a.ordernum from mt_order a 
		where a.paytime>='` + stime + `' and a.paytime<='` + etime + `' and (a.status=2 or a.status=3)`)
	if orderCar == nil {
		json["msg"] = "无成交订单"
		json["status"] = 0
		return
	}
	if t == "ordernum" {
		var ordernum []string
		for _, v := range orderCar {
			ordernum = append(ordernum, v["ordernum"].(string))
		}
		json["ordernum"] = ordernum
		json["status"] = 1
		return
	}
	orderCar = models.Query(`select a.ordernum,a.uid,a.carid,a.money,a.paytime,a.content,a.name from mt_order a 
		where a.ordernum in(` + ordernums + `)`)
	for carIndex, car := range orderCar {
		var allOrders []interface{}
		orders := models.Query(`select a.gid from mt_order_car a 
		where a.id in(` + car["carid"].(string) + `) and a.status>1 group by a.gid`)
		for _, order := range orders {
			ordersData := make(map[string]interface{})
			gid := order["gid"].(string)
			if gid == "0" {
				order["shopName"] = "统采商城"
			} else {
				order["shopName"] = models.Query(`select name from mt_shop where id=?`, gid)[0]["name"]
			}
			ordersData["shopId"] = gid
			ordersData["shopName"] = order["shopName"]
			var orderContent []interface{}
			shopcar := models.Query(`select a.num,a.uid,a.spec,a.price,b.id,b.title,b.number,b.bid from mt_order_car a 
				left join mt_product b on a.pid=b.id 
				where a.id in(` + car["carid"].(string) + `) and a.status>1`)
			for _, pro := range shopcar {
				ctn := make(map[string]interface{})
				brandFold := "100"
				brand := models.Query(`select fold from mt_brand_classify
					where find_in_set(?,uid) and find_in_set(?,bid) and status=1`, pro["uid"], pro["bid"])
				if brand != nil {
					if brand[0]["fold"] != nil {
						brandFold = brand[0]["fold"].(string)
					}
				}
				ctn["title"] = pro["title"]
				ctn["productId"] = pro["id"]
				price := pro["price"].(string)
				ctn["price"] = sword.Divi(sword.Mult(price, brandFold), "100")
				ctn["spec"] = pro["spec"]
				ctn["number"] = pro["number"]
				ctn["num"] = pro["num"]
				orderContent = append(orderContent, ctn)
			}
			ordersData["orderInfo"] = orderContent
			allOrders = append(allOrders, ordersData)
		}
		car["msg"] = car["content"]
		car["content"] = allOrders
		delete(orderCar[carIndex], "carid")
	}
	json["status"] = 1
	json["data"] = orderCar
}
